import React, { useState } from "react";
import {
  Box,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell,
  IconButton,
  Paper,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  CssBaseline,
  ThemeProvider,
} from "@mui/material";
import { Add, Edit, Delete } from "@mui/icons-material";
import theme from "../themes/theme ";

// 模型配置
const modelConfigs = [
  {
    name: "数据治理评估模型",
    fields: [
      { label: "满意度", key: "satisfaction", type: "qualitative", options: ["高", "中", "低"] },
      { label: "数字化人才占比", key: "talentRatio", type: "quantitative" },
      { label: "业务流程数字化率", key: "processRatio", type: "quantitative" },
    ],
  },
  {
    name: "业务流程评估模型",
    fields: [
      { label: "流程标准化程度", key: "standardization", type: "qualitative", options: ["高", "中", "低"] },
      { label: "自动化率", key: "automation", type: "quantitative" },
    ],
  },
];
const projectOptions = ["智能客服优化", "数据治理平台建设", "流程自动化改造", "知识库升级"];
interface Project {
  id: number;
  name: string; // 项目名称
  owner: string; // 负责人
  model: string; // 模型名称
  evaluations: Record<string, string | number>;
}

const TargetManagementPage: React.FC = () => {
  const [projects, setProjects] = useState<Project[]>([
    {
      id: 1,
      name: "智能客服优化",
      owner: "张三",
      model: "数据治理评估模型",
      evaluations: { 满意度: "高", 数字化人才占比: 30, 业务流程数字化率: 60 },
    },
  ]);

  const [openDialog, setOpenDialog] = useState(false);
  const [editingProject, setEditingProject] = useState<Project | null>(null);
  const [formData, setFormData] = useState<Project>({
    id: 0,
    name: "",
    owner: "",
    model: "",
    evaluations: {},
  });

  // 打开对话框
  const handleOpenDialog = (project?: Project) => {
    if (project) {
      setEditingProject(project);
      setFormData({ ...project });
    } else {
      setEditingProject(null);
      setFormData({ id: 0, name: "", owner: "", model: "", evaluations: {} });
    }
    setOpenDialog(true);
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
  };

  // 保存项目
  const handleSave = () => {
    if (editingProject) {
      setProjects((prev) =>
        prev.map((p) => (p.id === editingProject.id ? formData : p))
      );
    } else {
      setProjects((prev) => [...prev, { ...formData, id: Date.now() }]);
    }
    handleCloseDialog();
  };

  // 删除项目
  const handleDelete = (id: number) => {
    setProjects((prev) => prev.filter((p) => p.id !== id));
  };

  // 当前选择的模型配置
  const currentModelConfig = modelConfigs.find((m) => m.name === formData.model);

  return (
<ThemeProvider theme={theme}>
      <CssBaseline />
    <Box p={3}>
      <Typography variant="h5" gutterBottom>
        智能化项目目标设定管理
      </Typography>
      <Button
        variant="contained"
        startIcon={<Add />}
        onClick={() => handleOpenDialog()}
        sx={{ mb: 2 }}
      >
        新增目标设定
      </Button>

      <Paper>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>项目名称</TableCell>
              <TableCell>模型名称</TableCell>
              <TableCell>负责人</TableCell>
              <TableCell align="right">操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {projects.map((p) => (
              <TableRow key={p.id}>
                <TableCell>{p.name}</TableCell>
                <TableCell>{p.model}</TableCell>
                <TableCell>{p.owner}</TableCell>
                <TableCell align="right">
                  <IconButton color="primary" onClick={() => handleOpenDialog(p)}>
                    <Edit />
                  </IconButton>
                  <IconButton color="error" onClick={() => handleDelete(p.id)}>
                    <Delete />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
            {projects.length === 0 && (
              <TableRow>
                <TableCell colSpan={4} align="center">
                  暂无项目
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </Paper>

      {/* 新增/编辑 Dialog */}
      <Dialog open={openDialog} onClose={handleCloseDialog} fullWidth maxWidth="sm">
        <DialogTitle>{editingProject ? "编辑项目" : "新增目标设定"}</DialogTitle>
        <DialogContent>
          <FormControl margin="dense" fullWidth>
            <InputLabel>项目名称</InputLabel>
            <Select
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            >
            {projectOptions.map((p) => (
                <MenuItem key={p} value={p}>
                {p}
                </MenuItem>
            ))}
            </Select>
        </FormControl>
          <TextField
            margin="dense"
            label="负责人"
            fullWidth
            value={formData.owner}
            onChange={(e) => setFormData({ ...formData, owner: e.target.value })}
          />

          <FormControl margin="dense" fullWidth>
            <InputLabel>模型名称</InputLabel>
            <Select
              value={formData.model}
              onChange={(e) =>
                setFormData({ ...formData, model: e.target.value, evaluations: {} })
              }
            >
              {modelConfigs.map((m) => (
                <MenuItem key={m.name} value={m.name}>
                  {m.name}
                </MenuItem>
              ))}
            </Select>
          </FormControl>

          {/* 动态生成模型评估域 */}
          {currentModelConfig &&
  currentModelConfig.fields.map((field) => (
    <Box key={field.key} mt={2}>
      {field.type === "qualitative" ? (
        // 定性字段：下拉框
        <FormControl fullWidth>
          <InputLabel>{field.label}</InputLabel>
          <Select
            value={(formData.evaluations[field.label] as string) || ""}
            onChange={(e) =>
              setFormData({
                ...formData,
                evaluations: {
                  ...formData.evaluations,
                  [field.label]: e.target.value,
                },
              })
            }
          >
            {field.options?.map((opt) => (
              <MenuItem key={opt} value={opt}>
                {opt}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      ) : (
        // 定量字段：百分比输入
        <TextField
          type="number"
          label={field.label}
          fullWidth
          value={(formData.evaluations[field.label] as number) || ""}
          onChange={(e) => {
            let val = Number(e.target.value);
            if (val > 100) val = 100;
            if (val < 0) val = 0;
            setFormData({
              ...formData,
              evaluations: {
                ...formData.evaluations,
                [field.label]: val,
              },
            });
          }}
          InputProps={{
            endAdornment: <span style={{ marginLeft: 8 }}>%</span>,
          }}
        />
      )}
    </Box>
  ))}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>取消</Button>
          <Button onClick={handleSave} variant="contained">
            保存
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
 </ThemeProvider>   
  );
};

export default TargetManagementPage;
